<?php

/**
 * Translations module
 *
 * @author coder_
 */

class Translations extends _Module
{
    private static $instance;
    private $dependencies = array('Db', 'Url');

    private $languageFile;
    private $languages;
    private $langList = array();
    private $currentLang;
    private $db;

    private function __construct()
    {
    }

    private function __clone()
    {
    }

    public static function &getInstance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self;
        }
        return self::$instance;
    }

    public function initialize()
    {
        $path = CONFIGS . '/languages.xml';
        if (file_exists($path)) $this->languageFile = $path;

        $this->loadLanguagesFile();
        $this->currentLang = (string)$this->languages->default;
        foreach($this->languages as $lang)
        {
            $this->langList[] = $lang->code;
        }
        $uri = getModule('Url')->getUriArray();
        $this->checkRequestLanguage($uri);

        $this->db = getModule('Db');
    }

    public function getDependencies()
    {
        return $this->dependencies;
    }

    public function getTranslation($label = null)
    {
        if(is_null($label)) return;

        $string = $this->db->getSingle('SELECT `a`.`Text` FROM `translations` AS `a`
                                        LEFT JOIN `labels` AS `b`
                                        ON `a`.`LabelID` = `b`.`ID`
                                        WHERE `b`.`Name` = :name AND `a`.`Language` = :lang',
                                        array('name' => $label,'lang' => $this->currentLang));
        return $string ? $string : '';
    }

    public function setTranslation($lang, $label, $trans)
    {
        if(!in_array($lang, $this->langList)) return false;

        $id = $this->db->getSingle('SELECT `ID` FROM `labels` WHERE `Name` = ?', array($label));

        if(!$id)
        {
            $this->db->exec('INSERT INTO `labels` (`Name`) VALUES(?)', array($label));
            $id = $this->db->getLastInsertedId();
        }

        $this->db->exec('REPLACE INTO `translations` (`LabelID`, `Language`, `Text`) VALUES(:id, :lang, :text)',
                    array('id' => $id, 'lang' => $lang, 'text' => $trans));

        return true;
    }

    private function checkRequestLanguage($uri)
    {
        if(!isset($uri[0])) return;

        foreach($this->languages as $lang)
        {
            if((string)$lang->code == $uri[0])
            {
                $this->currentLang = (string)$lang->code;
                getModule('Session')->lang = $this->currentLang;
                unset($uri[0]);
                getModule('Url')->setUriArray(array_values($uri));
                getModule('Url')->reload();
            }
        }
    }

    private function loadLanguagesFile()
    {
        if($this->languageFile) {
            $this->languages = simplexml_load_file($this->languageFile);
        }
    }
}